#coding=utf-8
"""
用户登陆以及权限相关模块
"""
from tornado.web import authenticated
from tornado_json import schema
from tornado_json.exceptions import APIError
import logging
from .base import BaseApiHandler
from ..models import User
from ..tools import unblock, md5

# 取得logger
logger = logging.getLogger('AuthApi')

class AuthHandler(BaseApiHandler):
    """
    权限handler
    """
    __url_names__ = []
    __urls__ = [r'/api/auth']

    @unblock
    def get(self):
        """
        获取登陆成功后的用户信息
        """
        # 获取用户id
        user_id = self.get_current_user()
        if user_id:
            # 查询用户
            user = self.db_conn.query(User).filter(User.user_id == user_id)\
                .first()
            # 返回信息
            self.success(user)
        else:
            self.error('用户未登录')


class LoginHandler(AuthHandler):
    """
    登陆的handler
    """
    __urls__ = [r'/api/login']

    @schema.validate(
        input_schema={
            "required": ["username", "password"],
            "type": "object",
            "properties": {
                "username": {"type": "string"},
                "password": {"type": "string"},
            },
        },
        output_schema={
            "type": "null"
        }
    )
    @unblock
    def post(self):
        """
        登陆验证
        """
        logger.debug(self.json_args)
        # 查询
        user_id = self.json_args.get('username')
        password = self.json_args.get('password')
        # TODO:session过期时间设置
        remember = self.json_args.get('remember')
        user = self.db_conn.query(User).filter(User.user_id == user_id).first()
        logger.debug(user)
        if user and user.password == md5(password):
            # 登陆成功
            # TODO:session过期时间设置
            expires_days = None
            if remember:
                expires_days = 30
            # 记录cookie
            logger.info(user_id)
            self.set_secure_cookie('user', user_id, expires_days=expires_days)
            return
        else:
            # 登陆失败
            raise APIError(500, '登陆失败')


class LogoutHandler(AuthHandler):
    """
    登出的handler
    """
    __urls__ = [r'/api/logout']

    @unblock
    def get(self):
        """
        登出
        """
        self.clear_cookie('user')
        self.success(None)
